﻿<?php
    define("Token", "123456Aa");
    $wechatObj = new wechatCallbackapiTest();
    if($_GET["echostr"]){
        $wechatObj->valid();
    }else{
        $wechatObj->responseMsg();
    }
    class wechatCallbackapiTest{
        public function valid(){
            $echoStr = $_GET["echostr"];    
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
    
    
    public  function responseMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if(!empty($postStr)){
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $Event = trim($postObj->Event);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FunFlag>0</FuncFlag>
                    </xml>";
        if($Event == "subscribe"){
            $texTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>1</ArticleCount>
                    <Articles>
                    <item>
		    <Title><![CDATA[欢迎]]></Title>
                    <Description><![CDATA[欢迎大家学习]]></Description>
                    </item>
                    </Articles>
                    </xml>";
                    $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time);
                    echo $resultStr;
        }
        }
    }
    
        private  function checkSignature(){
            if(!defined("TOKEN")){
            throw  new Exception("TOKEN is not define");
            }
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            
            $token = TOKEN;
            $tmpArr = array($token,$timestamp,$nonce);
            sort($tmpArr,SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            
            if($tmpStr == $signature){
                return true;
            }else{
                return false;
            }
        }
    }
    
    